<script setup>
	import { reactive, ref } from 'vue';
	import { loginByPassword } from '@/services/user';
	import { useUserStore } from '@/stores/user';

	const form = reactive({
		mobile: '',
		password: ''
	})
	const formRules = {
		mobile: {
		  rules: [
			{ required: true, errorMessage: '请填写手机号码' },
			{ pattern: '^1\\d{10}$', errorMessage: '手机号码格式不正确' },
		  ],
		},
		password: {
		  rules: [
			{ required: true, errorMessage: '请输入密码' },
			{ pattern: '^[0-9a-zA-z]{6,8}$', errorMessage: '6-8位字母数字组成' },
		  ],
		}
	}
	const userStore = useUserStore()
	const formRef = ref(null)
	const isAgree = ref(false)
	function onAgreeClick () {
		isAgree.value = !isAgree.value
	}
	
	// 点击登录
	async function onFormSubmit () {
		try {
			
			// 判断是否同意协议
			if (!isAgree.value) return uni.utils.toast('请先同意协议')
			
			const formData = await formRef.value.validate()
			
			const {
				code, 
				message,
				data
			} = await loginByPassword(form)
			
			if (code !== 10000) return uni.utils.toast(message)
			
			userStore.token = data.token
			
			// 临时跳转到首页面
			uni.switchTab({
				url: '/pages/index/index'
			})
		} catch (err) {
			console.log(err, 'err');
		}
	}
</script>
<template>
  <uni-forms class="login-form" ref="formRef" :model="form" :rules="formRules">
    <uni-forms-item name="mobile">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
		v-model="form.mobile"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <uni-easyinput
        type="password"
        placeholder="请输入密码"
        :input-border="false"
        placeholder-style="color: #C3C3C5"
		v-model="form.password"
      />
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="isAgree" color="#16C2A3" @click="onAgreeClick" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onFormSubmit">登 录</button>
    <navigator hover-class="none" class="uni-navigator" url=" ">
      忘记密码？
    </navigator>
  </uni-forms>
</template>

<script>
  export default {
    options: {
      styleIsolation: 'shared',
    },
  }
</script>

<style lang="scss">
  @import './styles.scss';
</style>
